PATHMac OS 8 Developer Documentation > Operating System Services > Multiprocessing Services >

Adding Multitasking Capability to Applications Using Multiprocessing Services

   

Using Critical Regions

If your tasks need access to code that is nonreentrant, (that is, only one task can be executing the code at any particular time), you must designate that code as being a critical region. You do so by calling the function MPCreateCriticalRegion . Doing so returns a critical region ID that you use to identify the region when you want to enter or exit it later. To enter a critical region, the task must call MPEnterCriticalRegion and specify the ID of the region to enter. This function acts much like the functions that wait on message queues and semaphores; if the critical region is not currently available, the task can wait for a specified time for it to become available (after which it will time out).

After the task has completed using the critical region, you must call MPExitCriticalRegion . Doing so "frees" the critical region so that another task that is waiting on it can enter. Note that a task can call MPEnterCriticalRegion multiple times during execution (as in a recursive call) as long as it balances each such call with MPExitCriticalRegion when it leaves the critical region.

Note that the area of code designated as a critical region is not "tagged" as such in any way. You must make sure that your code is synchronized to properly isolate the critical region. For example, if you have a critical region that will be shared by two different tasks, you must create the critical region outside the tasks that will require it and pass the critical region ID to the tasks. This method ensures that, even if multiple instances of a task were created and running, only one could access a particular critical region at a time.

If a task contains more than one critical region, each critical region must have its own unique ID; otherwise, a task entering a critical region may block another task from entering a different critical region.


© 1999 Apple Computer, Inc. – (Last Updated 07 May 99)